<template>
  <div class="content">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header content="详情" @back="goback"></el-page-header>
        <div class="card-box--setbtn" v-if="isEdit">
          <el-button @click="goback">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
      </div>
    </el-card>

    <el-card class="card-box form-box">
      <div>
        <!-- <el-row class="form-info" v-if="route.query.mode !== 'add'">
          <el-col :span="7" :offset="1"
            >创建人: {{ infoState.createUserName }}</el-col
          >
          <el-col :span="7">创建时间: {{ infoState.createTime }}</el-col>
          <el-col :xl="8" :lg="12">文档编号: {{ infoState.billNum }}</el-col>
        </el-row> -->
        <el-form
          ref="formRef"
          @submit.prevent
          :model="formState"
          :rules="Rules"
          label-width="120px"
        >
          <el-form-item
            label="文档名称"
            placeholder="请输入文档名称"
            prop="documentName"
          >
            <el-input
              v-model="formState.documentName"
              class="width-custom220"
              :disabled="!isEdit"
            />
          </el-form-item>
          <el-form-item
            label="所属项目"
            placeholder="请选择所属项目"
            prop="projectName"
          >
            <el-select
              v-model="formState.projectName"
              clearable
              placeholder="请选择"
              value-key="id"
              :disabled="!isEdit"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectName"
                :value="item"
              ></el-option>
              <!-- <el-option :value="projectList">
                <el-tree
                  class="tree-option"
                  :data="projectList"
                  accordion
                  node-key="id"
                  ref="projectTreeRef"
                  highlight-current
                  :props="defaultProps"
                  @check-change="handleCheckChange"
                  check-on-click-node
                  :expand-on-click-node="false"
                >
                </el-tree>
              </el-option> -->
            </el-select>
          </el-form-item>

          <el-form-item label="项目文档来源" prop="projectPhaseName">
            <el-select
              v-model="formState.projectPhaseName"
              clearable
              value-key="dicCode"
              :disabled="!isEdit"
            >
              <el-option
                class="default-option"
                v-for="item in projectPhaseList"
                :label="item.dicValue"
                :key="item.dicCode"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="公开范围">
            <el-radio-group
              v-model="publicScope"
              :disabled="!isEdit"
              @change="handleChangePublic"
            >
              <el-radio :label="2">全部公开</el-radio>
              <el-radio :label="3">项目组内公开</el-radio>
              <el-radio :label="1">选定人员公开</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" v-if="publicScope === 3">
            <span>选择项目组：</span>
            <!-- <el-select v-model="formState.documentName">
              <el-option
                v-for="item in [1, 2, 3]"
                :label="item"
                :key="item"
                :value="item"
              ></el-option>
            </el-select> -->
            <el-select
              v-model="publicIds"
              clearable
              multiple
              filterable
              value-key="id"
              placeholder="请选择"
              :disabled="!isEdit"
              @change="handlePublicProject"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectName"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" v-if="publicScope === 1">
            <span>选择成员：</span>
            <el-select
              clearable
              v-model="publicIds"
              filterable
              :disabled="!isEdit"
              multiple
              remote
              value-key="id"
              :remote-method="query => getTableLeaderData(query, 'public')"
              placeholder="请输入姓名搜索"
              @change="handlePublicUser"
            >
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.name"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="下载权限">
            <el-radio-group
              v-model="dowloadScope"
              :disabled="!isEdit"
              @change="handleChangeDownload"
            >
              <el-radio :label="2">所有人可下载</el-radio>
              <el-radio :label="3">项目组成员可下载</el-radio>
              <el-radio :label="1">选定人员可下载</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" v-if="dowloadScope === 3">
            <span>选择项目组：</span>
            <el-select
              v-model="dowloadIds"
              clearable
              multiple
              filterable
              value-key="id"
              placeholder="请选择"
              :disabled="!isEdit"
              @change="handleDownLoadProject"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectName"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" v-if="dowloadScope === 1">
            <span>选择成员：</span>
            <el-select
              v-model="dowloadIds"
              clearable
              filterable
              multiple
              remote
              value-key="id"
              :remote-method="query => getTableLeaderData(query, 'down')"
              :disabled="!isEdit"
              placeholder="请输入姓名搜索"
              @change="handleDownLoadUser"
            >
              <el-option
                v-for="item in downUserList"
                :key="item.id"
                :label="item.name"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-row>
            <el-col :span="12">
              <el-form-item label="上传文档" prop="documentAttachmentArr">
                <el-upload
                  v-if="isEdit"
                  name="uploadFile"
                  multiple
                  :accept="acceptTypes"
                  :action="uploadComUrl"
                  :headers="uploadHeaders"
                  :on-success="handleSuccess"
                  :on-remove="handleRemove"
                  :on-error="handleError"
                  :file-list="defaultFileList"
                  :before-upload="beforeAvatarUpload"
                  :on-preview="handlePreview"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
                    </div>
                  </template>
                </el-upload>

                <template v-else>
                  <div
                    v-for="item in formState.documentAttachmentArr"
                    :key="item?.uuidFile"
                  >
                    <el-link
                      icon="el-icon-folder"
                      @click.prevent="handleDownload(item)"
                    >
                      {{ item.fileName }}&emsp;
                    </el-link>
                    <br />
                  </div>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="描述">
            <el-input
              v-model="formState.remarks"
              type="textarea"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import * as api from "/@/api/document";
import { postProjectList2 } from "/@/api/project";
import { getUsersForScience } from "/@/api/user";
import { useUpload } from "/@/hooks";
import { storageLocal } from "/@/utils/storage";
const {
  handleError,
  beforeAvatarUpload,
  uploadComUrl,
  acceptTypes,
  uploadHeaders,
  onInitFileList
} = useUpload();
const handlePreview = (item: any) => {
  window.open(
    `${location.origin}${location.pathname}#/online?uuidFile=${item?.response.data.uuidFile}&fileName=${item?.response.data.fileName}`
  );
};
const handleDownload = (item: any) => {
  window.open(
    `${location.origin}${location.pathname}#/online?uuidFile=${item.uuidFile}&fileName=${item.fileName}`
  );
};

// const projectRef = ref<HTMLElement | null>(null) as any;
// const projectTreeRef = ref<HTMLElement | null>(null) as any;
const formRef = ref<HTMLFormElement | null>(null) as any;

const router = useRouter();
const route = useRoute();

let projectList = ref([]);
let documentTypeList = ref([]);
let projectPhaseList = ref([]);
let copyProjectPhaseList = ref([]);
let userList = ref([]);
let downUserList = ref([]);
let publicScope = ref(2);
let publicIds = ref([]);

let dowloadScope = ref(2);
let dowloadIds = ref([]);

const formState = reactive({
  documentName: "",
  projectName: null,
  projectManageId: "",
  documentTypeName: null,
  documentTypeCode: "",
  projectPhaseName: null,
  projectPhaseCode: "",
  remarks: "",
  documentAttachmentArr: [],
  authItems: []
});

const Rules = {
  documentName: [
    { required: true, message: "请输入文档名称", trigger: "blur" }
  ],
  projectName: [
    { required: true, message: "请选择所属项目", trigger: "change" }
  ],

  projectPhaseName: [
    { required: true, message: "请选择项目阶段", trigger: ["change"] }
  ],
  documentAttachmentArr: [
    { required: true, message: "请上传文档", trigger: "change" }
  ]
};

// const defaultProps = {
//   children: "children",
//   label: "projectName",
//   id: "id"
// };

// let infoState = reactive({
//   createTime: "",
//   createUserName: "",
//   billNum: ""
// });

let isEdit = computed(() => {
  // @ts-ignore
  if (["add", "edit"].includes(route.query.mode)) {
    return true;
  } else {
    return false;
  }
});

/* 上传 -- start */
let defaultFileList = ref([]);

const handleRemove = (file, fileList) => {
  defaultFileList.value = fileList;
  formState.documentAttachmentArr = formState.documentAttachmentArr.filter(
    item => {
      const uuid = file.response ? file.response.data.uuidFile : file.uuidFile;
      return item.uuidFile !== uuid;
    }
  );
};

const handleSuccess = (res, file, fileList) => {
  if (res.code === 200) {
    defaultFileList.value = fileList;
    formState.documentAttachmentArr.push(res.data);
  }
  formRef.value.clearValidate();
};

/* 上传 -- end */

const handleChangePublic = event => {
  console.log(event, "event");
  publicIds.value = [];
  formState.authItems = formState.authItems.filter(item => {
    return item?.operType !== "R";
  });
  if (event === 1) {
    const info = storageLocal.getItem("rdms-info");
    publicIds.value.push({
      id: info.userId,
      name: info.name
    });
    formState.authItems.push({
      itemId: info.userId,
      itemType: event,
      operType: "R",
      itemName: info.name
    });
    if (userList.value.findIndex(el => el.id === info.userId) === -1) {
      userList.value.push({
        id: info.userId,
        name: info.name
      });
    }
  }
};

const handlePublicProject = item => {
  console.log(item);
  const newAuthItems = [];
  publicIds.value.forEach(i => {
    const project = projectList.value.find(el => el.id === i.id);
    newAuthItems.push({
      itemId: i.id,
      itemType: publicScope.value,
      operType: "R",
      itemName: project.projectName
    });
  });
  formState.authItems = formState.authItems.filter(i => {
    return i.operType === "D";
  });

  formState.authItems = formState.authItems.concat(newAuthItems);
  formState.authItems = uniqWith(formState.authItems);
};

const handlePublicUser = item => {
  console.log(item);
  const newAuthItems = [];
  publicIds.value.forEach(i => {
    newAuthItems.push({
      itemId: i.id,
      itemType: publicScope.value,
      operType: "R",
      itemName: i.name
    });
    if (userList.value.findIndex(el => el.id === i.id) === -1) {
      userList.value.push({
        id: i.id,
        name: i.name
      });
    }
  });
  formState.authItems = formState.authItems.filter(i => {
    return i.operType === "D";
  });

  formState.authItems = formState.authItems.concat(newAuthItems);
  formState.authItems = uniqWith(formState.authItems);
};

const handleChangeDownload = event => {
  console.log(event, "event");
  dowloadIds.value = [];
  formState.authItems = formState.authItems.filter(item => {
    return item?.operType !== "D";
  });
  if (event === 1) {
    const info = storageLocal.getItem("rdms-info");
    dowloadIds.value.push({
      id: info.userId,
      name: info.name
    });
    formState.authItems.push({
      itemId: info.userId,
      itemType: event,
      operType: "D",
      itemName: info.name
    });
    if (downUserList.value.findIndex(el => el.id === info.userId) === -1) {
      downUserList.value.push({
        id: info.userId,
        name: info.name
      });
    }
  }
};

const handleDownLoadProject = item => {
  console.log(item);
  const newAuthItems = [];
  dowloadIds.value.forEach(i => {
    const project = projectList.value.find(el => el.id === i.id);
    newAuthItems.push({
      itemId: i.id,
      itemType: dowloadScope.value,
      operType: "D",
      itemName: project.projectName
    });
  });
  formState.authItems = formState.authItems.filter(i => {
    return i.operType === "R";
  });

  formState.authItems = formState.authItems.concat(newAuthItems);
  formState.authItems = uniqWith(formState.authItems);
};

const handleDownLoadUser = item => {
  console.log(item);
  const newAuthItems = [];
  dowloadIds.value.forEach(i => {
    newAuthItems.push({
      itemId: i.id,
      itemType: dowloadScope.value,
      operType: "D",
      itemName: i.name
    });

    if (downUserList.value.findIndex(el => el.id === i.id) === -1) {
      downUserList.value.push({
        id: i.id,
        name: i.name
      });
    }
  });
  formState.authItems = formState.authItems.filter(i => {
    return i.operType === "R";
  });

  formState.authItems = formState.authItems.concat(newAuthItems);
  formState.authItems = uniqWith(formState.authItems);
};

// 去重
function uniqWith(arr) {
  // 缓存用于记录
  const cache = [];
  for (const t of arr) {
    // 检查缓存中是否已经存在
    if (cache.find(c => c.itemId === t.itemId && c.operType === t.operType)) {
      // 已经存在说明以前记录过，现在这个就是多余的，直接忽略
      continue;
    }
    // 不存在就说明以前没遇到过，把它记录下来
    cache.push(t);
  }
  // 记录结果就是过滤后的结果
  return cache;
}

// const handleSelected = val => {
//   if (val) {
//     formState.projectPhaseName = "";
//     const oldStage = JSON.parse(val.projectStage);
//     const newStage = copyProjectPhaseList.value.filter(item => {
//       if (oldStage.includes(item.dicCode)) {
//         return item;
//       }
//     });
//     projectPhaseList.value = newStage;
//     nextTick(() => {
//       formRef.value.clearValidate();
//     });
//   }
// };

const goback = () => {
  router.push("/document/manage");
};

const getDetail = async () => {
  try {
    const params = {
      id: route.query.id
    };
    const { code, data } = await api.getDocumentInfo(params);
    if (code === 200) {
      const {
        // createTime,
        // createUserName,
        // billNum,
        documentName,
        projectName,
        projectManageId,
        documentTypeName,
        documentTypeCode,
        projectPhaseName,
        projectPhaseCode,
        remarks,
        documentAttachmentArr,
        authItems
      } = data;

      // infoState.createTime = createTime;
      // infoState.createUserName = createUserName;
      // infoState.billNum = billNum;

      formState.documentName = documentName;
      formState.projectName = projectName;
      formState.projectManageId = projectManageId;

      //  回显项目
      formState.projectName = {
        id: +projectManageId,
        projectName: projectName
      };

      formState.documentTypeName = {
        dicValue: documentTypeName,
        dicCode: documentTypeCode
      };
      formState.documentTypeCode = documentTypeCode;
      formState.projectPhaseName = {
        dicValue: projectPhaseName,
        dicCode: projectPhaseCode
      };
      formState.projectPhaseCode = projectPhaseCode;
      formState.remarks = remarks;
      formState.documentAttachmentArr = documentAttachmentArr;
      defaultFileList.value = onInitFileList(documentAttachmentArr);

      // const currentProject = projectList.value.find(item => {
      //   return item.id === +projectManageId;
      // });

      // const oldStage = JSON.parse(currentProject?.projectStage ?? '"[]"');
      // const newStage = copyProjectPhaseList.value.filter(item => {
      //   if (oldStage.includes(item.dicCode)) {
      //     return item;
      //   }
      // });
      // projectPhaseList.value = newStage;

      formState.authItems = authItems;
      authItems.forEach(item => {
        if (item.operType === "R" && item.itemType == "1") {
          publicScope.value = 1;
        } else if (item.operType === "R" && item.itemType == "3") {
          publicScope.value = 3;
        } else if (item.operType === "D" && item.itemType == "1") {
          dowloadScope.value = 1;
        } else if (item.operType === "D" && item.itemType == "3") {
          dowloadScope.value = 3;
        }
      });

      const pub = authItems.filter(item => {
        return item.operType === "R" && publicScope.value === +item.itemType;
      });

      pub.map(i => {
        publicIds.value.push({
          id: +i.itemId,
          name: i.itemName
        });
        if (publicScope.value === 3) {
          if (projectList.value.findIndex(el => el.id === +i.itemId) === -1) {
            projectList.value.push({
              id: +i.itemId,
              projectName: i.itemName
            });
          }
        } else if (publicScope.value === 1) {
          if (userList.value.findIndex(el => el.id === +i.itemId) === -1) {
            userList.value.push({
              id: +i.itemId,
              name: i.itemName
            });
          }
        }
      });

      const dow = authItems.filter(item => {
        return item.operType === "D" && dowloadScope.value === +item.itemType;
      });
      dow.map(i => {
        dowloadIds.value.push({
          id: +i.itemId,
          name: i.itemName
        });
        if (dowloadScope.value === 3) {
          if (projectList.value.findIndex(el => el.id === +i.itemId) === -1) {
            projectList.value.push({
              id: +i.itemId,
              projectName: i.itemName
            });
          }
        } else if (dowloadScope.value === 1) {
          if (downUserList.value.findIndex(el => el.id === +i.itemId) === -1) {
            downUserList.value.push({
              id: +i.itemId,
              name: i.itemName
            });
          }
        }
      });

      if (
        projectList.value.findIndex(
          el => el.id === formState.projectName.id
        ) === -1
      ) {
        projectList.value.push(formState.projectName);
      }
    }
  } catch (err) {
    console.log(err);
  }
};

const handleSubmit = () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      const copyFormData = JSON.parse(JSON.stringify(formState));
      copyFormData.documentTypeName = "项目文件";
      copyFormData.documentTypeCode = "1";
      copyFormData.projectPhaseName = formState.projectPhaseName.dicValue;
      copyFormData.projectPhaseCode = formState.projectPhaseName.dicCode;
      copyFormData.projectName = formState.projectName.projectName;
      copyFormData.projectManageId = formState.projectName.id;

      if (route.query.mode === "add") {
        const { code, message } = await api.onAdd(copyFormData);
        console.log(code, message);
        if (code === 200) {
          NotifMessage.success("保存成功");
          goback();
        } else {
          NotifMessage.error(message);
        }
      } else {
        const { code, message } = await api.onSave(
          Object.assign(copyFormData, { id: route.query.id })
        );
        if (code === 200) {
          NotifMessage.success("修改成功");
          goback();
        } else {
          NotifMessage.error(message);
        }
      }
    } else {
      return false;
    }
  });
};

// 获取项目信息
const getProjectList = async () => {
  try {
    const { code, data } = await postProjectList2({ pageNum: 1, pageSize: 0 });
    if (code === 200) {
      projectList.value = data.list;
    }
  } catch (err) {
    console.log(err);
  }
};

// 文档类型
const initDoucumentTypeList = async () => {
  try {
    const params = {
      dicType: "rd_doc_type"
    };
    const { code, data } = await api.postDictList(params);
    if (code === 200) {
      documentTypeList.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

// 项目阶段
const initProjectPhaseList = async () => {
  try {
    const params = {
      dicType: "rd_project_stage"
    };
    const { code, data } = await api.postDictList(params);
    if (code === 200) {
      projectPhaseList.value = data;
      copyProjectPhaseList.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

async function getTableLeaderData(query = "", type) {
  try {
    const params = {
      pageNum: 1,
      pageSize: 200,
      nameLike: query
    };
    const { code, data } = await getUsersForScience(params);
    if (code === 200) {
      if (type === "public") {
        userList.value = data.list.map(item => {
          return {
            id: item.id,
            name: item.name + (item.deptName ? "-" + item.deptName : "-无")
          };
        });
      } else if (type === "down") {
        downUserList.value = data.list.map(item => {
          return {
            id: item.id,
            name: item.name + (item.deptName ? "-" + item.deptName : "-无")
          };
        });
      }
    }
  } catch (err) {
    console.log(err);
  }
}

initDoucumentTypeList();

onMounted(async () => {
  await getProjectList();
  await initProjectPhaseList();

  if (route.query.mode !== "add") {
    await getDetail();
  }
});
</script>

<style lang="scss" scoped>
.content {
  :deep .el-page-header__content {
    font-size: 16px;
  }
  .card-box {
    margin-bottom: 10px;
    &--headerwrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    &--setbtn {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      width: 140px;
    }
  }

  .header__wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.form-box {
  margin-top: 10px;
}
.form-info {
  margin-bottom: 20px;
}
.header-btns {
  text-align: right;
}

// .el-select-dropdown__item {
//   height: auto;
//   // min-height: 100px;
//   // max-height: 274px;
//   padding: 0;
//   overflow-x: hidden;
//   overflow-y: hidden;
// }
// .el-select-dropdown_item.selected {
//   font-weight: normal;
// }

// .el-select-dropdown_item.selected {
//   font-weight: normal;
// }

// // .tree-option
// .tree-option :deep .el-tree-node__content {
//   height: auto;
//   padding: 0 10px;
// }
// // .tree-option :deep .el-select-dropdown__list {
// //   padding: 0 6px;
// // }
// .tree-option :deep .el-tree-node__label {
//   font-weight: normal;
//   padding: 0 10px;
//   margin-right: 10px;
// }

// .el-tree :deep .is-current .el-tree-node__label {
//   color: #409eff;
//   font-weight: 700;
// }
// .el-tree :deep .is-current .el-tree-node__children .el-tree-node__label {
//   color: #606266;
//   font-weight: normal;
// }
// .default-option :deep .el-tree-node__label {
//   font-weight: normal;
//   padding: 0 10px;
//   // margin-right: 10px;
// }

// .default-option {
//   padding: 0 10px;
// }
</style>
